package in.muton.edushare.components.tasks.electives.api;

import in.muton.edushare.EduShareSession;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.CurriculumDAO;
import com.edushare.common.vo.Courses;
import com.edushare.common.vo.Curricula;
import com.edushare.common.vo.Users;

public class CommonElectives implements Serializable {

	public CommonElectives(IModel<Users> user, IModel<Curricula> curr, int semester) {
		this.curr = curr;
		this.semester = semester;
		init();
	}

	private void init() {
		CurriculumDAO cDAO = new CurriculumDAO(EduShareSession.get()
				.getSessionORMInterface());
		Integer electives = cDAO.getNumElectives(curr.getObject(), semester);
		boolean incrementElectives = true;
		List<Integer> currList = null;
		for (int i = 0; i < electives; i++) {
			incrementElectives = true;
			if (!listContains(i)) {
				for (int j = i + 1; j < electives; j++) {
					List<Courses> courseSet1 = cDAO.getElectiveCourses(curr
							.getObject(), semester, i);
					List<Courses> courseSet2 = cDAO.getElectiveCourses(curr
							.getObject(), semester, j);
					
					if(isElectiveSetSame(courseSet1, courseSet2)){
						if(incrementElectives){
							numCommonElectives++;
							currList = new ArrayList<Integer>();
							commonElectiveGroupIds.add(currList);
							currList.add(i);
							incrementElectives = false;
						}
						currList.add(j);
					}
				}
			}
		}
	}

	private boolean isElectiveSetSame(List<Courses> courseSet1,
			List<Courses> courseSet2) {
		if (courseSet1.containsAll(courseSet2)
				&& courseSet2.containsAll(courseSet1))
			return true;
		return false;
	}

	private boolean listContains(int i) {
		for (List<Integer> k : commonElectiveGroupIds) {
			for (Integer j : k) {
				if (j.equals(i))
					return true;
			}
		}
		return false;
	}

	public Integer getNumCommonElectives() {
		return numCommonElectives;
	}

	//Only those elective numbers which have duplicates.
	public List<List<Integer>> getCommonElectiveGroupIds() {
		return commonElectiveGroupIds;
	}
	
	public boolean isCommonElective(Integer i){
		return listContains(i);
	}

	private Integer numCommonElectives = 0;
	private List<List<Integer>> commonElectiveGroupIds = new ArrayList<List<Integer>>();
	private IModel<Curricula> curr;
	private Integer semester;

	private static final long serialVersionUID = 2898926641899969045L;
}
